﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.APP.SysApprovalService;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using Telerik.Web.UI;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class MP_PositionWorkOnDuty : System.Web.UI.Page
    {
        private IEmployeeTypeBLL etBLL = new EmployeeTypeBLL();
        private IEmployeeBLL eBll = new EmployeeBLL();
        private IPositionBLL posBLL = new PositionBLL();
        Main main = new Main();
        SsMng ssMng = new SsMng();

        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!IsPostBack)
            {
                LoadWorkOnDutyCbb();
                BindModel();
                BindUi();
            }
        }
        
        private void LoadDataGrid()
        {
            var ds = posBLL.SelectWorkOnDuty();
            RadGrid1.DataSource = ds;
            RadGrid1.DataBind();
        }

        private void BindUi()
        {
            if(Request["do"] == "edit")
            {
                lblDoWhat.Text = "แก้ไขข้อมูลรักษาการ";
                iconDoWhat.ImageUrl = "~/App_UI/Images/Buttons/edit.gif";
                pnlEditor.Visible = true;
                pnlIndex.Visible = false;
                pnlSendApproval.Visible = false;
                pnlDetail.Visible = false;
            }else if(Request["do"] == "create")
            {
                lblDoWhat.Text = "สร้างข้อมูลรักษาการใหม่"; 
                iconDoWhat.ImageUrl = "~/App_UI/Images/Buttons/AddRecord.gif";
                pnlEditor.Visible = true;
                pnlIndex.Visible = false;
                pnlSendApproval.Visible = false;
                pnlDetail.Visible = false;
            }else if(Request["do"] == "index")
            {
                lblDoWhat.Text = (from e in eBll.ListEmployees() where e.RecordStatus != "D" && e.Position!=null && e.Position.Sequence.ToString() == Request["pos_seq"] select "ข้อมูลรักษาการของ " + e.Person.FullName).FirstOrDefault();
                iconDoWhat.ImageUrl = "~/App_UI/Images/Buttons/SinglePlus.gif";
                LoadDataGrid();
                pnlEditor.Visible = false;
                pnlIndex.Visible = true;
                pnlSendApproval.Visible = false;
                pnlDetail.Visible = false;
            } else if(Request["do"] == "askApproval")
            {
                var model = posBLL.SelectWorkOnDutyById(Convert.ToInt32(Request["sequence"]));
                lblDoWhat.Text = "ส่งขออนุมัติรักษาการ";
                iconDoWhat.ImageUrl = "~/App_UI/Images/Buttons/mail_gr.gif";
                pnlEditor.Visible = false;
                pnlIndex.Visible = false;
                pnlSendApproval.Visible = true;
                pnlDetail.Visible = true;
                txbRequestTitle.Text = string.Format("ขออนุมัติ{0}ทำหน้าที่รักษาการแทน{1} ในช่วง{2}-{3}", model.by_emp_name, model.to_emp_name, model.start_date.ToString("d/M/yy"), model.end_date.ToString("d/M/yy"));
                txbRequestDescription.Text = model.description;
                
                string strServer = HttpContext.Current.Request.Url.Host;
                string strUrlPrefix = string.IsNullOrEmpty(ConfigurationSettings.AppSettings["SubSystem"]) ? "" : "/" + ConfigurationSettings.AppSettings["SubSystem"];
                string serverPath = !HttpContext.Current.Request.Url.IsDefaultPort ? "http://localhost:60830/" : string.Format("http://{0}{1}/WEB.GIMS/", strServer, strUrlPrefix);
                string strTaskUrl = string.Format("../Task/ApprovePath?appPrcGrpId={1}&applytoEmpId={2}&relatedToPosId={3}&createdByEmpId={4}",
                                                          null, 2, model.by_emp_seq, model.to_pos_seq, model.created_by);
                var sAuthen = new GerpAuthenService.GerpAuthenService();
                string tokenKey = sAuthen.CreateOTP(ssMng.EmpSeqI, true, strTaskUrl);
                string strUrl = string.Format("{0}Home/SingleSigon?&tokenKey={1}", serverPath, tokenKey);
                      
                iframe1.Attributes["src"] = strUrl; 

            } else if(Request["do"] == "detail")
            {
                var model = posBLL.SelectWorkOnDutyById(Convert.ToInt32(Request["sequence"]));
                lblDoWhat.Text = "ข้อมูลรักษาการ";
                iconDoWhat.ImageUrl = "~/App_UI/Images/Buttons/mail_gr.gif";
                pnlEditor.Visible = false;
                pnlIndex.Visible = false;
                pnlSendApproval.Visible = false;
                pnlDetail.Visible = true;
                txbRequestTitle.Text = string.Format("ขออนุมัติ{0}ทำหน้าที่รักษาการแทน{1} ในช่วง{2}-{3}", model.by_emp_name, model.to_emp_name, model.start_date.ToString("d/M/yy"), model.end_date.ToString("d/M/yy"));
                txbRequestDescription.Text = model.description;

                // find task
                int? taskId;
                bool temp;
                new SysApprovalService.SysApprovalService().GetTaskIdOfRef(2, true, model.wod_seq, true, out taskId, out temp);

                if(taskId.HasValue)
                {
                    string strServer = HttpContext.Current.Request.Url.Host;
                    string strUrlPrefix = string.IsNullOrEmpty(ConfigurationSettings.AppSettings["SubSystem"]) ? "" : "/" + ConfigurationSettings.AppSettings["SubSystem"];
                    string serverPath = !HttpContext.Current.Request.Url.IsDefaultPort ? "http://localhost:60830/" : string.Format("http://{0}{1}/WEB.GIMS/", strServer, strUrlPrefix);
                    string strTaskUrl = string.Format("../Task/Details/{0}?EmptyLayout=true", taskId);
                    var sAuthen = new GerpAuthenService.GerpAuthenService();
                    string tokenKey = sAuthen.CreateOTP(ssMng.EmpSeqI, true, strTaskUrl);
                    string strUrl = string.Format("{0}Home/SingleSigon?&tokenKey={1}", serverPath, tokenKey);
                      
                    iframe1.Attributes["src"] = strUrl;
                }

            }

            if(hdfRecordStatus.Value == "D")
            {
                Response.Write("ข้อมูลถูกลบ");
                Response.End();
            }
        }

        private void BindModel()
        {
            int? sequence = !String.IsNullOrEmpty(Request["Sequence"]) ? Convert.ToInt32(Request["Sequence"]) : (int?)null;
            int? posSeq = !String.IsNullOrEmpty(Request["pos_seq"]) ? Convert.ToInt32(Request["pos_seq"]) : (int?)null;
            //int? empSeq = !String.IsNullOrEmpty(Request["emp_seq"]) ? Convert.ToInt32(Request["emp_seq"]) : (int?)null;
            WorkOnDuty model = null;
            if(sequence.HasValue) 
            {
                model = posBLL.SelectWorkOnDutyById(sequence.Value);
            } else if(posSeq.HasValue)
            {
                //if (empSeq.HasValue && !posSeq.HasValue)
                //{
                //    EmployeeBLL employeeBll = new EmployeeBLL();
                //    var employee = employeeBll.ListEmployees(empSeq.ToString()).FirstOrDefault();
                //    posSeq = employee.Position.Sequence;
                //}

                model = new WorkOnDuty
                    {
                        to_pos_seq = posSeq.Value,
                        start_date =   DateTime.Now.Date,
                        end_date = DateTime.Now.Date.AddHours(23).AddMinutes(59),
                        record_status = "W",
                        created_by = ssMng.EmpSeqI,
                        see_old_message = true,
                        created_when = DateTime.Now
                    };
            }
            else
            {
                Response.Write("Please create work on duties via GHRMS menu");
            }

            if(model == null)
            {
                Response.Redirect("MP_PositionWorkOnDuty.aspx?do=index&pos_seq=" + Request["pos_seq"]);
            }
            
            hdfSequence.Value = model.wod_seq.ToString();
            lblRefNo.Text = hdfRefNo.Value = model.ref_no;
            radCbbWorkOnDutyToPosition.SelectedValue = model.to_pos_seq.ToString();
            ltrToEmpName.Text = model.to_emp_name;
            radCbbWorkOnDutyByEmployee.SelectedValue = model.by_emp_seq.ToString();
            foreach(RadComboBoxItem byEmpItem in radCbbWorkOnDutyByEmployee.Items)
            {
                byEmpItem.Visible = byEmpItem.Value != model.to_pos_seq.ToString();
            }
            ltrByEmpName.Text = model.by_emp_name;
            dtpWorkOnDutyStart1.SelectedDate = model.start_date;
            ltrStartDate.Text = model.start_date.ToString("dd/MM/yyyy HH:mm");
            dtpWorkOnDutyEnd1.SelectedDate = model.end_date;
            ltrEndDate.Text = model.end_date.ToString("dd/MM/yyyy HH:mm");
            rblSeeOldMessage.SelectedValue = model.see_old_message ? "1" : "0";
            ltrSeeOldMessage.Text = model.see_old_message ? "ให้มองเห็นข้อความเก่าและจัดการอนุมัติแทนได้" : "ให้เห็นเฉพาะข้อความที่ถูกส่งมาในช่วงรักษาการ";
            hdfRecordStatus.Value = model.record_status;
            hdfCreatedBy.Value = Convert.ToString(model.created_by);
            hdfCreatedWhen.Value = Convert.ToString(model.created_when);
            hdfUpdatedBy.Value = Convert.ToString(model.updated_by);
            hdfUpdatedWhen.Value = Convert.ToString(model.updated_when);
            Delete.Visible = model.wod_seq != 0;
        }

        private void LoadWorkOnDutyCbb()
        {
            var ds = posBLL.ListPositions();
            var dse = eBll.ListEmployees();
            radCbbWorkOnDutyToPosition.DataSource = ds;
            radCbbWorkOnDutyByEmployee.DataSource = dse;
            try
            {
                radCbbWorkOnDutyByEmployee.DataBind();
                radCbbWorkOnDutyToPosition.DataBind();
                radCbbWorkOnDutyByEmployee.SelectedIndex = 0;
                radCbbWorkOnDutyToPosition.SelectedIndex = 0;
            }catch{}
        }

        protected void Save_Click(object sender, EventArgs e)
        {
            EmployeeInfo workOnDutyEmployeeBy;
            PositionInfo workOnDutyPositionTo;
            DateTime workOnDutyStart;
            DateTime workOnDutyEnd;
            bool seeOldMessage;
            var workOnDutyEmpSeqBy = radCbbWorkOnDutyByEmployee.SelectedValue;
            var workOnDutyPosSeqTo = radCbbWorkOnDutyToPosition.SelectedValue;
            var allEmp = eBll.ListEmployees();
            workOnDutyEmployeeBy = allEmp.FirstOrDefault(o => o.Sequence.ToString() == workOnDutyEmpSeqBy);
            workOnDutyPositionTo = posBLL.ListPositions().FirstOrDefault(o => o.Sequence.ToString() == workOnDutyPosSeqTo);
            if (workOnDutyEmployeeBy == null || workOnDutyPositionTo == null || 
                dtpWorkOnDutyStart1.SelectedDate == null || dtpWorkOnDutyEnd1.SelectedDate == null)
            {
                main.MessageAlert(Page, "Not found employee " + workOnDutyEmpSeqBy + ", " + workOnDutyPosSeqTo);
                return;
            }
            workOnDutyStart = dtpWorkOnDutyStart1.SelectedDate.Value;
            workOnDutyEnd = dtpWorkOnDutyEnd1.SelectedDate.Value;
            seeOldMessage = rblSeeOldMessage.SelectedValue == "1";

            int wodSeq = Convert.ToInt32(string.IsNullOrEmpty(hdfSequence.Value) ? "0" : hdfSequence.Value);
            WorkOnDuty wod = new WorkOnDuty();
            wod.wod_seq = wodSeq;
            wod.ref_no = hdfRefNo.Value;
            wod.by_emp_seq = Convert.ToInt32(workOnDutyEmpSeqBy);
            wod.to_pos_seq = Convert.ToInt32(workOnDutyPosSeqTo);
            wod.start_date = workOnDutyStart;
            wod.end_date = workOnDutyEnd;
            wod.see_old_message = seeOldMessage;
            wod.description = txbDescription.Text;
            wod.record_status = hdfRecordStatus.Value;
            wod.created_by = main.ConvertNullInt(hdfCreatedBy.Value).Value;
            wod.created_when = main.ConvertNullDateTime(hdfCreatedWhen.Value).Value;
            wod.updated_by = main.ConvertNullInt(hdfUpdatedBy.Value);
            wod.updated_when = main.ConvertNullDateTime(hdfUpdatedWhen.Value);

            wod = wodSeq == 0 ? posBLL.InsertWorkOnDuty(wod) : posBLL.UpdateWorkOnDuty(wod);

            if(wod != null)
            {
                main.MessageAlert(Page, "บันทึก" + (wodSeq == 0 ? "เพิ่ม":"แก้ไข") +"ข้อมูลผู้รักษาการเรียบร้อยแล้ว");
                Response.Redirect("MP_PositionWorkOnDuty.aspx?pos_seq=" + Request["pos_seq"] + "&do=index");  
            }else
            {
                main.MessageAlert(Page, "บันทึกข้อมูลผู้รักษาการไม่สำเร็จ");
            }

        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            posBLL.DeleteWorkOnDuty(new WorkOnDuty{updated_by = ssMng.EmpSeqI, wod_seq = Convert.ToInt32(Request["Sequence"])});
            main.MessageAlert(Page,"ลบข้อมูลผู้รักษาการเรียบร้อยแล้ว");
            BindModel();
            BindUi();
        }

        protected void lbtCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("MP_PositionWorkOnDuty.aspx?do=create&pos_seq=" + Request["pos_seq"]);
        }

        protected void lbtGotoIndex_Click(object sender, EventArgs e)
        {
            var pos_seq = string.IsNullOrEmpty(Request["pos_seq"]) 
                ? posBLL.SelectWorkOnDutyById(Convert.ToInt32(Request["sequence"])).to_pos_seq.ToString()
                : Request["pos_seq"];
            Response.Redirect("MP_PositionWorkOnDuty.aspx?do=index&pos_seq=" + pos_seq);
        }
         
        protected void AskApproval(object sender, CommandEventArgs e)
        {
            var sequence = Convert.ToInt32(e.CommandArgument);
            Response.Redirect(string.Format("MP_PositionWorkOnDuty.aspx?do=askApproval&sequence={0}&pos_seq={1}", sequence, Request["pos_seq"])); 
        }

        protected void ConfirmSendApproval(object sender, EventArgs e)
        {
            var model = posBLL.SelectWorkOnDutyById(Convert.ToInt32(hdfSequence.Value));
            using(var service = new SysApprovalService.SysApprovalService())
            {
                CreateTaskVM v = new CreateTaskVM();
                v.AppPrcGrpId = 15;
                v.AppPrcGrpIdSpecified = true;
                v.ApplyToEmpId = model.by_emp_seq;
                v.ApplyToEmpIdSpecified = true;
                v.CreateByEmpId = model.created_by;
                v.CreateByEmpIdSpecified = true;
                //v.RelatedToEmpId = model.to_emp_seq;
                //v.RelatedToEmpIdSpecified = true;
                v.Remark = txbRequestDescription.Text;
                v.Title = txbRequestTitle.Text;
                v.TaskCode = hdfRefNo.Value;
                v.ConfirmAs = "P";
                v.ApproveAs = "A";
                v.RefId = model.wod_seq;
                v.RefIdSpecified = true;
                var result = service.CreateTask(v);
                if(!string.IsNullOrEmpty(result.CreateErrorResult))
                {
                    string errorMessageJavascript = "เกิดปัญหาระหว่างสร้างคำขอ: " + result.CreateErrorResult;
                    main.MessageAlert(Page, errorMessageJavascript);
                }else
                {
                    main.MessageAlert(Page, "สร้างคำขออนุมัติสำเร็จ");
                    Response.Redirect(string.Format("MP_PositionWorkOnDuty.aspx?do=detail&sequence={0}&pos_seq={1}", model.wod_seq, Request["pos_seq"])); 
                }
            }
        }

        protected void Detail(object sender, CommandEventArgs e)
        {
            var sequence = Convert.ToInt32(e.CommandArgument);
            Response.Redirect(string.Format("MP_PositionWorkOnDuty.aspx?do=detail&sequence={0}&pos_seq={1}", sequence, Request["pos_seq"])); 
        }
    }
}